#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <windows.h>

#define MAX_NETWORKS 100

/* 定义路由表项结构体 */
typedef struct
{
    char network[MAX_NETWORKS];
    int hops;
    char next_hop[MAX_NETWORKS];
} RouteEntry;

/* 比较函数，用于 qsort 排序 */
int compare(const void *a, const void *b)
{
    return strcmp(((RouteEntry *)a)->network, ((RouteEntry *)b)->network);
}

/* 查找网络在路由表中的索引 */
int find_index(RouteEntry *table, int size, const char *network)
{
    for (int i = 0; i < size; i++)
    {
        if (strcmp(table[i].network, network) == 0)
        {
            return i;
        }
    }
    return -1;
}

int main()
{
    SetConsoleOutputCP(65001);

    RouteEntry r1_table[MAX_NETWORKS];
    RouteEntry r2_message[MAX_NETWORKS];
    int r1_size = 0, r2_size = 0;

    /* 模拟输入R1的路由表 */
    sprintf(r1_table[r1_size].network, "N1");
    r1_table[r1_size].hops = 1;
    sprintf(r1_table[r1_size].next_hop, "R1");
    r1_size++;

    sprintf(r1_table[r1_size].network, "N2");
    r1_table[r1_size].hops = 0;
    sprintf(r1_table[r1_size].next_hop, "直接发送");
    r1_size++;

    sprintf(r1_table[r1_size].network, "N3");
    r1_table[r1_size].hops = 6;
    sprintf(r1_table[r1_size].next_hop, "R4");
    r1_size++;

    sprintf(r1_table[r1_size].network, "N4");
    r1_table[r1_size].hops = 8;
    sprintf(r1_table[r1_size].next_hop, "R5");
    r1_size++;

    /* 模拟输入R2发来的路由表 */
    sprintf(r2_message[r2_size].network, "N2");
    r2_message[r2_size].hops = 2;
    sprintf(r2_message[r2_size].next_hop, "R5");
    r2_size++;

    sprintf(r2_message[r2_size].network, "N3");
    r2_message[r2_size].hops = 3;
    sprintf(r2_message[r2_size].next_hop, "R6");
    r2_size++;

    sprintf(r2_message[r2_size].network, "N4");
    r2_message[r2_size].hops = 7;
    sprintf(r2_message[r2_size].next_hop, "R7");
    r2_size++;

    sprintf(r2_message[r2_size].network, "N5");
    r2_message[r2_size].hops = 3;
    sprintf(r2_message[r2_size].next_hop, "R8");
    r2_size++;

    /* 执行RIP协议更新算法 */
    for (int i = 0; i < r2_size; i++)
    {
        int index = find_index(r1_table, r1_size, r2_message[i].network);
        if (index == -1)
        { // 新网络
            r1_table[r1_size] = r2_message[i];
            r1_size++;
        }
        else
        {
            if (r2_message[i].hops < r1_table[index].hops)
            {
                r1_table[index] = r2_message[i];
            }
        }
    }

    /* 按网络名排序路由表 */
    qsort(r1_table, r1_size, sizeof(RouteEntry), compare);

    /* 输出更新后的R1路由表 */
    printf("R1更新后的路由表:\n");
    for (int i = 0; i < r1_size; i++)
    {
        printf("网络: %s, 跳数: %d, 下一跳: %s\n", r1_table[i].network, r1_table[i].hops, r1_table[i].next_hop);
    }

    return 0;
}